package com.hustmed.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ShortKeyUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public  String dataToShortKey(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(obj);
        String shortKey = IdUtils.simpleUUID();
        stringRedisTemplate.opsForValue().set("SHORTKEY:" + shortKey, jsonString, 1, TimeUnit.DAYS);
        return shortKey;
    }

    public JSONObject shortKeyToData(String shortKey) {
        String strJson = stringRedisTemplate.opsForValue().get("SHORTKEY:" + shortKey);
        JSONObject jobj = JSONObject.parseObject(strJson);
        return jobj;
    }

    public String idTo64 (String id){
        int length = id.length();
        String pre10 = id.substring(0,10);
        String last = id.substring(10,length);
        BigInteger num1 = new BigInteger(pre10,64);
        BigInteger num2= new BigInteger(last,64);

        return "";
    }

    public static String[] chars = new String[] { "2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    /**
     * <li>短8位UUID思想其实借鉴微博短域名的生成方式，但是其重复概率过高，而且每次生成4个，需要随即选取一个。
     * <li>本算法利用56个可打印字符，通过随机生成32位UUID，由于UUID都为十六进制，所以将UUID分成8组，每4个为一组，然后通过模56操作，结果作为索引取出字符，
     * <li>这样重复率大大降低。
     * <li>建议:表的编码字段加唯一索引
     * @return
     */
    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x38]);
        }
        return shortBuffer.toString();
    }


}
